<template>
    <div>
        <el-breadcrumb >
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item >用户列表</el-breadcrumb-item>
        </el-breadcrumb>

        <div class="user-btns">
            <el-button type="primary" @click="dialogFormVisible=true">添加用户</el-button>
            <el-button type="danger" @click="deleteUsers">删除用户</el-button>
            <el-input placeholder="请选择用户" icon="search" v-model="searchname" style="width:200px"></el-input>
            <el-button @click="search">搜索用户</el-button>
        </div>


        <el-table
            ref="multipleTable"
            :data="userlist"
            border
            tooltip-effect="dark"
            style="width: 100%"
            @selection-change="handleSelectionChange">

            <el-table-column
            type="selection"
            width="55">
            </el-table-column>

            <el-table-column
            prop="name"
            label="用户名"
            width="160">
            </el-table-column>

            <el-table-column
            prop="password"
            label="密码"
            width="340">
            </el-table-column>

            <el-table-column
            prop="sex"
            label="性别"
            width="120">
            </el-table-column>

            <el-table-column
            prop="date"
            label="生日日期"
            width="200">
            <template scope="scope">{{ scope.row.date }}</template>
            </el-table-column>

            <el-table-column label="操作">
                <template scope="scope">
                    <el-button
                    size="small"
                    @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button
                    size="small"
                    type="danger"
                    @click.native.prevent="deleteRow(scope.$index,scope.row,userlist)"
                    >删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <div class="list-footer">
            <el-pagination
            small
            layout="prev, pager, next"
            :page-size="8"
            :total="total" 
            @current-change="handleCurrentChange"
            >
            </el-pagination>
        </div>

        <el-dialog title="添加用户" :visible.sync="dialogFormVisible"  >
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px">
              <el-form-item label="用户名" prop="name" >
                <el-input v-model="ruleForm.name" placeholder="字母丶数字 5-8位"></el-input>
              </el-form-item>

              <el-form-item label="密码" prop="pass">
                <el-input v-model="ruleForm.password" type="password" :disabled="true"></el-input>
              </el-form-item>
              
              <el-form-item label="性别" prop="sex">
                <el-radio class="radio" v-model="ruleForm.sex" label="男">男</el-radio>
                <el-radio class="radio" v-model="ruleForm.sex" label="女">女</el-radio>
              </el-form-item>

              <el-form-item prop="date" label="生日">
                <el-date-picker type="date" placeholder="选择日期" v-model="ruleForm.date" @change="dateChange" style="width: 100%;"></el-date-picker>
              </el-form-item>

              <el-form-item label="状态" prop="status">
                <el-switch on-text="启用" off-text="禁用" v-model="ruleForm.status"></el-switch>
              </el-form-item>

              <el-form-item label="提醒" >
                <p>初始密码为<strong>123456</strong></p>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="submitForm('ruleForm')">添加用户</el-button>
                <el-button @click="resetForm('ruleForm')">取消</el-button>
              </el-form-item>
            </el-form>
        </el-dialog>

        <el-dialog title="编辑用户" :visible.sync="editdialog"  >
            <el-form :model="editForm" :rules="editrules" ref="editForm" label-width="100px">
              <el-form-item label="用户名" prop="name" >
                <el-input v-model="editForm.name" placeholder="字母丶数字 5-8位" :disabled="true"></el-input>
              </el-form-item>

              <el-form-item label="密码" prop="pass">
                <el-input v-model="editForm.password" type="password" :disabled="true"></el-input>
              </el-form-item>
              
              <el-form-item label="性别" prop="sex">
                <el-radio class="radio" v-model="editForm.sex" label="男">男</el-radio>
                <el-radio class="radio" v-model="editForm.sex" label="女">女</el-radio>
              </el-form-item>

              <el-form-item prop="date" label="生日">
                <el-date-picker type="date" placeholder="选择日期" v-model="editForm.date" @change="dateChange" style="width: 100%;"></el-date-picker>
              </el-form-item>

              <el-form-item label="状态" prop="status">
                <el-switch on-text="启用" off-text="禁用" v-model="editForm.status"></el-switch>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="submitEdit('editForm')">确定</el-button>
                <el-button @click="resetEdit('editForm')">取消</el-button>
              </el-form-item>
            </el-form>
        </el-dialog>
  </div>
</template>

<script>
import Axios from 'axios';
import MD5 from 'js-md5';
  export default {
    data() {
      var regName = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入用户名'));
        } else {
          var reg=/^[a-zA-Z0-9]{5,8}$/g;
          if(reg.test(value)){
             Axios({
              method:'post',
              url:'http://localhost:3000/users/find',
              data:{
                name:value,
              },
              dataType:'json'
            }).then((d)=>{
              if(d.data.msg){
                callback(new Error('用户名已存在'));
              }else{
                callback();
              }
            })
          }else{
            callback(new Error('用户名格式不正确'));
          }
        }
      }
      return {
        dialogFormVisible:false,//控制添加用户的dialog的显示
        editdialog:false,
        time:'',
        total:0,
        searchname:'',
        formLabelWidth: '150px',
        userlist: [],
        multipleSelection: [],
        editForm: {
          name: '',
          password: '',
          sex: '男',
          date: '',
          status:true,
        },
        ruleForm: {
          name: '',
          password: MD5('123456'),
          sex: '男',
          date: '',
          status:true,
        },
        rules: {
          name: [
            { validator: regName, trigger: 'blur' }
          ],
          date: [
            { type: 'date', required: true, message: '请选择日期', trigger: 'change' }
          ],
        },
      }
    },
    methods: {
      toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      //添加用户
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            Axios({
              method:'post',
              url:'http://localhost:3000/users/register',
              data:{
                name:this.ruleForm.name,
                password:this.ruleForm.password,
                sex:this.ruleForm.sex,
                date:this.time,
                status:this.ruleForm.status,
              },
              dataType:'json'
            }).then(d=>{
                if(!d.data.msg){
                  this.$message({
                    showClose: true,
                    message: '添加成功！',
                    type: 'success'
                  });
                  this.dialogFormVisible=false;
                  this.$refs['ruleForm'].resetFields();
                  this.initdata();
                }
            })
          } else {
            return false;
          }
        });
      },
      submitEdit(formName){
        this.$refs[formName].validate((valid) => {
          if (valid) {
            Axios({
              method:"post",
                url:'http://localhost:3000/users/updatepass',
                data:{
                    name:this.editForm.name,
                    password:this.editForm.password,
                    sex:this.editForm.sex,
                    date:this.time,
                    status:this.editForm.status,
                },
              dataType:'json',
            }).then(d=>{
                if(d){
                    this.$message({
                    showClose: true,
                    message: '修改成功！',
                    type: 'success'
                    });
                   this.initdata();
                   this.editdialog=false;
                }
            })
          } else {
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
        this.dialogFormVisible=false;
      },
      resetEdit(formName){
        this.$refs[formName].resetFields();
        this.editdialog=false;
      },
      dateChange(val){
        this.time = val;
      },
      handleCurrentChange(val){
        Axios({
          method:'post',
          url:'http://localhost:3000/users/list',
          data:{
            page:val,
            limit:8,
          },
          dataType:'json'
        }).then(d=>{
          this.userlist=d.data.docs;
        })
      },
      search(){
        Axios({
          method:'post',
          url:'http://localhost:3000/users/list',
          data:{
            name:this.searchname,
            page:1,
            limit:8,
          },
          dataType:'json'
        }).then(d=>{
          this.userlist=d.data.docs;
        })
      },
      //编辑按钮
      handleEdit(index, row) {
        console.log(index, row);
        this.editdialog = true;
        this.editForm = row;
      },
      deleteRow(index,row,rows) {
        rows.splice(index, 1);
        Axios({
          method:'post',
          url:'http://localhost:3000/users/removes',
          data:{
            name:row.name,
          },
          dataType:'json'
        }).then((res)=>{
          if(res.data.msg){
            this.$message({
              showClose: true,
              message: '删除成功！',
              type: 'success'
            });
          }
        })
      },
      deleteUsers(){
        var data=this.multipleSelection;
        var users=[];
        for(var i=0;i<data.length;i++){
          users.push(data[i].name);
        }
        Axios({
          method:'post',
          url:'http://localhost:3000/users/removeusers',
          data:{
            users:users,
          },
          dataType:'json'
        }).then((res)=>{
          if(res.data.msg){
            this.$message({
              showClose: true,
              message: '删除成功！',
              type: 'success'
            });
            this.initdata();
          }
        })
      },
      initdata(){
         Axios({
          method:'post',
          url:'http://localhost:3000/users/list',
          data:{
            page:1,
            limit:8,
          },
          dataType:'json'
        }).then(d=>{
          this.userlist=d.data.docs;
          this.total = d.data.total;
        })
      }
    },
    
    created(){
     this.initdata();
    }
  }
</script>
<style lang="scss">
    .user-btns{
        margin-bottom:10px;
    }
    .list-footer{
        margin-top:20px;
        float:right;
    }
</style>